import { Button, Card, Form, Input, Radio, Select } from 'antd'
import QRCode from 'qrcode'
import { useEffect, useMemo, useRef } from 'react'

export default () => {
  const [form] = Form.useForm()
  const qrcodeRef = useRef()

  useEffect(() => {
    form.setFieldsValue({ type: "input" })
  }, [])

  const options = useMemo(() => {
    const localData = window.localStorage.getItem('options')
    if (localData) {
      const data = JSON.parse(localData)
      return data
    }
    return []
  }, [])

  const createQrcode = () => {
    const { type, code } = form.getFieldsValue()
    let newOptions = []
    if (type === 'input') {
      const localData = window.localStorage.getItem("options")
      if (localData) {
        newOptions = JSON.parse(localData)
      }
      newOptions.push({
        label: code,
        value: code
      })
      window.localStorage.setItem("options", JSON.stringify(newOptions))
    }
    const ele = qrcodeRef.current
    QRCode.toCanvas(ele, code, (error) => {
      console.log(error)
    })
  }

  return (
    <div>
      <Card
        bordered
        styles={{
          body: {
            width: 500
          }
        }}
      >
        <Form form={form}>
          <Form.Item name='type'>
            <Radio.Group>
              <Radio value="input">输入</Radio>
              <Radio value="select">选择</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="编号" shouldUpdate>
            {({ getFieldsValue }) => {
              const type = getFieldsValue().type
              if (type === 'input') {
                return (
                  <Form.Item name="code" noStyle>
                    <Input />
                  </Form.Item>
                )
              }
              return (
                <Form.Item name="code" noStyle>
                  <Select options={options} />
                </Form.Item>
              )
            }}
          </Form.Item>
          <Button type='primary' onClick={() => createQrcode()}>生成</Button>
        </Form>
      </Card>
      <canvas ref={qrcodeRef} />
    </div >
  )
}